from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

class DetectionFace:
    mog_face_detection_func = None
    def __init__(self):
        self.mog_face_detection_func = pipeline(Tasks.face_detection, './model/iic/cv_resnet101_face-detection_cvpr22papermogface')
        print("-------初始化detection_face---------")
    def test(self):
        src_img_path = './data/images/mog_face_detection.jpg'
        raw_result = self.mog_face_detection_func(src_img_path)
        print('face detection output: {}.'.format(raw_result))

        # if you want to show the result, you can run
        from modelscope.utils.cv.image_utils import draw_face_detection_no_lm_result
        from modelscope.preprocessors.image import LoadImage
        import cv2
        import numpy as np

        # load image from url as rgb order
        src_img = LoadImage.convert_to_ndarray(src_img_path)
        # save src image as bgr order to local
        src_img  = cv2.cvtColor(np.asarray(src_img), cv2.COLOR_RGB2BGR)
        cv2.imwrite('src_img.jpg', src_img)
        # draw dst image from local src image as bgr order
        dst_img = draw_face_detection_no_lm_result('src_img.jpg', raw_result)
        # save dst image as bgr order to local
        cv2.imwrite('dst_img.jpg', dst_img)
        # show dst image by rgb order
        import matplotlib.pyplot as plt
        dst_img  = cv2.cvtColor(np.asarray(dst_img), cv2.COLOR_BGR2RGB)
        plt.imshow(dst_img)


        import matplotlib.pyplot as plt
        import matplotlib.patches as patches

        # 创建一个示例图像
        img = plt.imread('./data/images/mog_face_detection.jpg')  # 替换为你的图像路径
        plt.imshow(img)

        #框出所有以上检测到的人脸
        for coordinates_one in raw_result["boxes"]:

            # 指定矩形框的位置，coordinates 为 [xmin, ymin, xmax, ymax]
            coordinates = coordinates_one  # 这里替换为你的四个点的坐标
            xmin, ymin, xmax, ymax = coordinates

            # 计算宽度和高度
            width = xmax - xmin
            height = ymax - ymin

            # 创建一个红色矩形框
            rect = patches.Rectangle((xmin, ymin), width, height, linewidth=2, edgecolor='red', facecolor='none')

            # 将矩形框添加到图像中
            plt.gca().add_patch(rect)

        # 显示图像
        plt.axis('off')  # 不显示坐标轴
        plt.show()
    # 遍历视频帧
    def get_detected_face_collection(self,frame):
        raw_result = self.mog_face_detection_func(frame)
        return raw_result
if __name__ == '__main__':
    detection_face = DetectionFace()  # 创建类的实例
    detection_face.test()  # 调用 test 方法